<template>
    <el-upload
        class="upload-demo"
        action="/apis/base/upload/file"
        :headers="{ Authorization: 'Bearer ' + token }"
        :on-success="handleSuccess"
        :multiple="false"
        :on-error="handleError"
        :on-exceed="handleExceed"
        :show-file-list="true"
        :before-upload="beforeUpload"
        :on-change="changeFile"
        :file-list="fileList"
        ref="upload"
    >
        <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
</template>

<script>
import {mapState} from "vuex";

export default {
    data() {
        return {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('token')
            },
            fileList: []
        };
    },
    computed: {
        ...mapState(["token"]),
    },
    methods: {
        handleSuccess(response, file, fileList) {
            if (response.code == 200) {
                if (this.fileList.length > 0) {
                    this.fileList = []
                }
                this.fileList[0] = {name: response.data.originName, url: response.data.filePath}
                this.$emit("uploadSuccess", response, file, fileList)
            }
        },
        clearFiles() {
            this.fileList = [];
        },
        handleError(err) {
            // 处理上传失败的回调
        },
        beforeUpload(file) {
            // 定义允许的文件类型
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'];

            // 检查文件类型是否在允许的类型列表中
            if (!allowedTypes.includes(file.type)) {
                this.$message.error('只允许上传图片类型（如 jpg, png, gif, bmp）');
                return false;
            }

            // 检查文件大小是否超过限制
            if (file.size > 10 * 1024 * 1024) {
                this.$message.error('文件大小超过限制（10MB），请重新选择');
                return false;
            }

            // 如果文件类型和大小都符合要求，则返回 true 允许上传
            return true;
        },

        changeFile() {

        },
        handleExceed(files, fileList) {

        }
    }
}
;
</script>

<style>
.upload-demo {
    ul {
        li {
            transition: none !important;
        }
    }
}
</style>

<style scoped>
.upload-demo {
    margin-top: 10px;
}

</style>
